/**
 * Meituan.com Inc.
 * Copyright (c) 2010-2018 All Rights Reserved.
 */
package com.tuyou.cloud.ribbon.controller;

import com.tuyou.cloud.common.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * <p></p>
 *
 * @author tuyou@meituan.com
 * @version v0.1 2018-11-25 10:21 PM tuyou Exp $$
 */
@RestController
@RequestMapping("/request")
public class RestClientController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public String get() {
        ResponseEntity<String> responseEntity = restTemplate.
                getForEntity("http://hello-service/get?name={1}&age={2}", String.class, "tuyou", 25);
        String response = responseEntity.getBody();
        return "get:" + response;
    }

    @RequestMapping(value = "/put", method = RequestMethod.PUT)
    public String put() {
        User user = new User();
        user.setName("tuyou");
        user.setAge(25);
        restTemplate.put("http://hello-service/put/{1}", user, "1"); //put返回void
        return "put";
    }

    @RequestMapping(value = "/post", method = RequestMethod.POST)
    public String post() {
        User user = new User();
        user.setName("tuyou");
        user.setAge(25);
        ResponseEntity<String> responseEntity = restTemplate.
                postForEntity("http://hello-service/post?name={1}&age={2}", user, String.class, "tuyou", 25);
        String response = responseEntity.getBody();
        return "post:" + response;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public String delete() {
        restTemplate.delete("http://hello-service/delete/{1}", "1"); //delete返回void
        return "delete";
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("hello-service");
        return "serviceId:" + serviceInstance.getServiceId()
                + ",host:" + serviceInstance.getHost()
                + ",port:" + serviceInstance.getPort();
    }
}